﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using JumpNFight.Weapons;
using XDL.Framework;
using Microsoft.Xna.Framework.Content;

namespace JumpNFight.Screens
{
    abstract class BalisticWSRendererBase : 
        DrawableGameComponent
    {
        BalisticWeaponSystemBase m_grenadeLauncherWS;
        Texture2D m_weaponTexture;
        Texture2D m_inactiveWeaponTexture;
        SpriteFont m_debugFont;
        Texture2D m_blankTexture;

        /// <summary>
        /// Shared sprite batch (with the main rendering system)
        /// </summary>
        public SpriteBatch SpriteBatch
        {
            get;
            set;
        }

        public ContentManager Content
        {
            get;
            set;
        }

        protected abstract string WeaponSystemName
        {
            get;
        }

        public BalisticWSRendererBase(Game game) :
            base(game)
        {
        }

        protected override void LoadContent()
        {
            m_grenadeLauncherWS = GameServices.GetService<BalisticWeaponSystemBase>(WeaponSystemName);
            m_weaponTexture = Content.Load<Texture2D>(m_grenadeLauncherWS.Settings.Name + "Bullet");
            try
            {
                m_inactiveWeaponTexture = Content.Load<Texture2D>(m_grenadeLauncherWS.Settings.Name + "InactiveBullet");
            }
            catch(ContentLoadException)
            {
                // does nothing
            }
            m_debugFont = this.Content.Load<SpriteFont>("Debug");
            m_blankTexture = this.Content.Load<Texture2D>("Blank");
        }

        public override void Draw(GameTime gameTime)
        {
            // draw badguys
            Vector2 offset = new Vector2(m_weaponTexture.Width / 2, m_weaponTexture.Height / 2);
            foreach (BalisticWeaponBase it in m_grenadeLauncherWS.Entities)
            {
                Vector2 pos = it.Moveable.Position;
                if (GameServices.DebugDraw)
                    SpriteBatch.Draw(m_blankTexture, new Rectangle(it.Moveable.TileX * Simulation.World.UnitToPixel, it.Moveable.TileY * Simulation.World.UnitToPixel, 32, 32), Color.DarkRed);

                SpriteBatch.Draw(it.IsActive ? m_weaponTexture : m_inactiveWeaponTexture, new Rectangle((int)pos.X, (int)pos.Y, m_weaponTexture.Width * 2, m_weaponTexture.Height * 2), null, Color.White, 0, offset, SpriteEffects.None, 0);

                if (GameServices.DebugDraw)
                    SpriteBatch.DrawString(m_debugFont, string.Format("{0:#0.00}/{1:#0.00}\nGround:{2}\nLife:{3:#0.00}s\nSpeed:{4:#0.00}, {5:#0.00}", it.Moveable.X, it.Moveable.Y, it.Moveable.TouchingGround, it.Lifetime, it.Moveable.VX, it.Moveable.VY), pos + new Vector2(it.Moveable.Width, 0), Color.DarkRed);
            }            
        }
    }
}
